// bloc/ai_chat/ai_chat_bloc.dart (*** NEW ***)
import 'dart:async';
import 'dart:collection';
import 'dart:convert';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hive/hive.dart';
import 'package:zywz/api/api_client.dart';
import 'package:zywz/api/chat/ChatStreamService.dart';
import '../../api/api_client.dart' as AiResponse;
import '../../api/chat/ChatDataParser.dart';
import '../../api/chat/ChatStreamHandler.dart';
import '../../api/chat/api_chat_asyn.dart';
import '../../models/user.dart';
import 'ai_chat_event.dart';
import 'ai_chat_state.dart';

// ChatMessage(text: '请稍后, 正在分析贵公司企业数据。', isUser: false),
// ChatMessage(text: '受 ************有限公司委托, 我分析了从2021年01月01日至202'
// '4年11月30日购销链风险、发票风险及增值税、企业所得税等税收风险, 得出以下结论: 共检测8'
// '项风险指标结果: 其中: 高风险3项/中风险0项/低风险0项/无其他等级风险, 可能涉及虚开发票金额0'
// '万元(取销项影响金额)以上, 或涉及接受虚开金额310万元以上, 预计影响增值税0万元(取影响税额, 根据纳税人类型选择)以上。', isUser: false),


class AiChatBloc extends Bloc<AiChatEvent, AiState> {
  StreamSubscription<String>? _streamSubscription;
  AiChatBloc() : super(AiChatState(messages: [])) {
    on<SendMessage>(_onSendMessage);
    on<LoadMessage>(_onLoadMessage);
  }

  Future<void>  _onSendMessage(SendMessage event, Emitter<AiState> emit) async {
    // "aiType": 1,
    // "phone": "12312312312",
    // "sessionId": "12312312312_1",
    // "content": "你是谁",
    // "fileId": "askdhkajshfjahsf,aslkflaksfjklasjfkas,asdlkasjlkfjakljfa",
    // "partyId": "60074",
    // "bookName": "A公司

    final user = Hive.box<User>('user_box').get('currentUser');
    event.params['phone'] = user?.phone;
    event.params['aiType'] = '1';
    event.params['sessionId'] = '${user?.phone}_1';
    // event.params['content'] = event.params['content'];
    if(event.params['fileId'] == null || event.params['fileId'] == ''){
      event.params.remove('fileId');
    }
    event.params['partyId'] = '60074';
    event.params['bookName'] =  user?.appCompanyDto?.name ?? '';
    // 取消之前的订阅（如果有）
    await _streamSubscription?.cancel();


    // try {
    //   // 创建 ChatStreamHandler 实例
    //   final chatHandler = ChatStreamService();
    //
    //   // 关键：使用 await for 并检查 emit.isDone
    //   await for (final data in chatHandler.chatStream(event.params)) {
    //     // 检查事件处理器是否已完成
    //     // if (emit.isDone) break;
    //
    //     try {
    //       final chatMessage = ChatDataParser.parseStreamData(data);
    //       emit(AiChatStreamDataState(message: chatMessage));
    //     } catch (e) {
    //       emit(AiChatErrorState("数据解析错误: $e"));
    //     }
    //   }
    //
    //   // 检查事件处理器是否已完成
    //   // if (!emit.isDone) {
    //     emit(AiChatStreamCompleteState());
    //   // }
    // } catch (e) {
    //   // if (!emit.isDone) {
    //   //   emit(AiChatErrorState("请求失败: $e"));
    //   // }
    //   emit(AiChatErrorState("请求失败: $e"));
    // }


    try {
      await for (final message in    ChatStreamService().chatStream(event.params)) {

        // 解析JSON响应
        final jsonResponse = json.decode(message);
        // final aiResponse = AiResponse.fromJson(jsonResponse);
        final rejectStatus = (jsonResponse['output'] as Map<String, dynamic>)['reject_status'];
        final finish_reason = (jsonResponse['output'] as Map<String, dynamic>)['finish_reason'];
        final text = (jsonResponse['output'] as Map<String, dynamic>)['text'];
        print('rejectStatus:  $rejectStatus');
        print('finish_reason:  $finish_reason');
        print('finish_reason:  ${finish_reason?.runtimeType}');
        if(finish_reason == 'stop'){
          print('message:  $jsonResponse');
          // emit(AiChatErrorState("请求失败: $rejectStatus"));
          emit(AiChatSuccessRspState(messages: HashMap.from({'content': text, 'recordType': 'ai'}))) ;
        }

        // if(aiResponse['output']?.['x'] != null){
        //
        // }
        // final chatMessage = ChatDataParser.parseStreamData(message);
        // emit(AiChatSuccessRspState(messages: HashMap.from({'content': chatMessage, 'recordType': 'ai'}))) ;
      }
    } catch (e) {
      emit(AiChatSuccessRspState(messages: HashMap.from({'content': '再次发送请求', 'recordType': 'ai'}))) ;
    }

    // try {
    //   // 使用流式处理
    //   // 启动流式请求并监听数据
    //   _streamSubscription = ChatStreamService().chatStream(event.params).listen(
    //         (rawData) {
    //       // print('Stream data received: $rawData');
    //
    //       // 解析数据
    //       final chatMessage = ChatDataParser.parseStreamData(rawData);
    //       print("chatMessage emit.isDone:   ${emit.isDone}");
    //       print("chatMessage   :  $chatMessage");
    //       emit(AiChatSuccessRspState(messages: HashMap.from({'content': chatMessage, 'recordType': 'ai'}))) ;
    //       // 发送解析后的数据到 UI
    //       if (!emit.isDone) {
    //         // emit(AiChatStreamDataState(message: chatMessage));
    //
    //       }
    //     },
    //     onError: (error) {
    //       print('Stream error: $error');
    //       if (!emit.isDone) {
    //         emit(AiChatErrorState("流式请求错误: $error"));
    //       }
    //     },
    //     onDone: () {
    //       print('Stream completed');
    //       if (!emit.isDone) {
    //         emit(AiChatStreamCompleteState());
    //       }
    //     },
    //   );
    // } catch (e) {
    //   print('Exception: $e');
    //   if (!emit.isDone) {
    //     emit(AiChatErrorState("请求失败: $e"));
    //   }
    // }

  //   try {
  //
  //     ChatStreamHandler().handleChatStream(event.params).listen((event) {
  //       print('--------------handleChatStream---11111111111111----------》》》》》》aiChatList');
  //       print('aiChatList:  ${event}');
  //       print('--------------handleChatStream---22222222222222----------》》》》》》aiChatList');
  //     });
  //
  //     // final data = await ApiChatAsynClient.instance.chatSend(event.params);
  //     //
  //     // print('-----------------11111111111111----------》》》》》》aiChatList');
  //     // print('aiChatList:  ${data  ?? {}}');
  //     // print('-----------------22222222222222----------》》》》》》aiChatList');
  //     // emit(AiChatSendState(msgData: data ?? ''));
  //   } catch (e) {
  //     emit(AiChatSendState(msgData: ''));
  //   }
  }

  var  page =1;
  var  size = 10;

  Future<void> _onLoadMessage(LoadMessage event, Emitter<AiState> emit) async {
    final user = Hive.box<User>('user_box').get('currentUser');
    var mapParams = <String, dynamic>{};
    mapParams['phone'] = user?.phone;
    mapParams['aiType'] = '1';
    mapParams['page'] = page;
    mapParams['size'] = size;
    try {
      final data = await ApiClient.instance.getAiChatList(mapParams);

      print(data  ?? {});

      emit(AiChatSuccessState(messages: data?.data ?? {}));
    } catch (e) {
      emit(AiChatSuccessState(messages: {}));
    }
  }

  @override
  Future<void> close() {
    _streamSubscription?.cancel();
    return super.close();
  }

}
